package com.paomi.client.fragment.order.presenter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.paomi.client.R;
import com.paomi.client.activity.payMoney.model.PayMoneyBean;
import com.paomi.client.activity.payResult.ResultPayActivity;
import com.paomi.client.base.BaseLoadMorePresenter;
import com.paomi.client.base.BaseMvpLCEView;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.fragment.order.model.OrderListBean;
import com.paomi.client.net.Api;
import com.paomi.client.net.BaseCallback;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.PayResult;
import com.paomi.client.utils.PayUtil;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.view.LoadingDialog;
import com.paomi.client.widget.RxToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import butterknife.ButterKnife;
import retrofit2.Call;

/**
 * 待支付（付款）
 */
public class OrderCollPre extends BaseLoadMorePresenter<BaseMvpLCEView> {
    private List<OrderListBean.OrderData> orderDataList=new ArrayList<>();
    private String state=null;//订单状态 0 未支付 1 已支付 2 待发货 3 待收货 4 待评价（已收货） 5 已完成（已评价） 6 退款申请中 7 已退款
    private int pageN;//页码数
    public void getListOrder(String state,int pageN){
        this.state=state;
        this.pageN=pageN;
        loadData(true);
    }
    @Override
    protected void loadData(int page, int skip, boolean pullToRefresh) {
        if(state!=null){
            Api.getInstanceService(Constants.Ticket_URL).myOrderList(state,""+pageN,""+Constants.PAGE_SIZE).enqueue(new BaseCallback<OrderListBean>() {
                @Override
                public void onResponse(Call<OrderListBean> call, OrderListBean result) {
                    if (pageN==1){
                        orderDataList.clear();
                    }
                    orderDataList.addAll(result.getReturnData().getData());
                    if(isViewAttached()) {
                        //处理价格相同的归类
                        for(int i=0;i<orderDataList.size();i++){
                            OrderListBean.OrderData orderData=orderDataList.get(i);
                            List<OrderListBean.OrderGoods> goodsList=orderData.getOrderGoodsTickets();
                            Map<String,List<OrderListBean.OrderGoods>> orderMap=sortAmountList(goodsList);
                            orderData.setOrderList(orderMap);
                            //如果需要再次对分组后的数据进行操作,可以取出对应的数据
                            Set<String> keySet = orderMap.keySet();
                            List<OrderListBean.OrderGoods> goodsList1=new ArrayList<>();
                            for(String groupName : keySet) {
                                OrderListBean.OrderGoods ticketJson1 = new OrderListBean.OrderGoods();
                                ticketJson1.setAmount(Float.parseFloat(groupName));
                                ticketJson1.setNum(orderMap.get(groupName).size());
                                String stringType="";
                                for(OrderListBean.OrderGoods seatBean:orderMap.get(groupName)){
                                    stringType +=seatBean.getGoodsTicketName()+"、";
                                }
                                ticketJson1.setGoodsTicketName(stringType.substring(0,stringType.length()-1));
                                goodsList1.add(ticketJson1);
                            }
                            orderData.setOrderGoodsTickets(goodsList1);
                        }
                        getView().setData(orderDataList, true);
                    }
                }
            });
        }else{
            getView().setData(orderDataList, true);
        }
        if(orderDataList.size()==0){
            getView().setData(orderDataList, true);
        }
        if(orderDataList.size()==0){
            getView().setData(orderDataList, true);
        }
        LoadingDialog.get().hideLoading();
    }
    /**
     * 订单删除的操作
     *
     * @param activity
     */
    public void deleteBtn(Activity activity, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_delete_shaow, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView title = view.findViewById(R.id.title);
        title.setText(activity.getResources().getString(R.string.del_order));
        TextView msg_tv = view.findViewById(R.id.msg_tv);
        msg_tv.setText(activity.getResources().getString(R.string.delete_order));
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setText(activity.getResources().getString(R.string.no_btn));
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setText(activity.getResources().getString(R.string.yes_btn));
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getOrderDelete(id);
            }
        });
    }
    /**
     *用户-订单-确认收货
     * @param orderId
     */
    public void getOrderConfim(String orderId){
        Api.getInstanceService(Constants.Ticket_URL).orderConfirm(orderId).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                result.returnMessage="确认收货";
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        EventBus.getDefault().post(result);
                    }
                }, 100);
            }
        });
    }
    /**
     *用户-订单-删除
     * @param orderId
     */
    public void getOrderDelete(String orderId){
        Api.getInstanceService(Constants.Ticket_URL).orderDelete(orderId).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                result.returnMessage="订单删除";
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        EventBus.getDefault().post(result);
                    }
                }, 100);
            }
        });
    }
    /**
     * 订单取消的操作
     *
     * @param activity
     */
    public void deleteCancel(Activity activity, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_delete_shaow, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView title = view.findViewById(R.id.title);
        title.setText(activity.getResources().getString(R.string.clear_order));
        TextView msg_tv = view.findViewById(R.id.msg_tv);
        msg_tv.setText(activity.getResources().getString(R.string.cancel_order));
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setText(activity.getResources().getString(R.string.no_btn));
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setText(activity.getResources().getString(R.string.yes_btn));
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getOrderCancel(id);
            }
        });
    }
    /**
     *用户-订单-取消
     * @param orderId
     */
    public void getOrderCancel(String orderId){
        Api.getInstanceService(Constants.Ticket_URL).orderCancel(orderId).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                result.returnMessage="订单取消";
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        EventBus.getDefault().post(result);
                    }
                }, 100);
            }
        });
    }
    /**
     * 支付订单的操作
     *
     * @param activity
     */
    public void setPayNow(Activity activity, Typeface iconfont, OrderListBean.OrderData paySureJson) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.pay_type_layout, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        ButterKnife.bind(dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView chartTv=dialog.findViewById(R.id.chart_tv);
        TextView btnWeChart=dialog.findViewById(R.id.btn_we_chart);
        TextView aliPay=dialog.findViewById(R.id.ali_pay);
        TextView btnAliPay=dialog.findViewById(R.id.btn_aliPay);
        chartTv.setTypeface(iconfont);
        btnWeChart.setTypeface(iconfont);
        aliPay.setTypeface(iconfont);
        btnAliPay.setTypeface(iconfont);
        btnWeChart.setOnClickListener(new View.OnClickListener() {//微信选中
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                btnAliPay.setText(activity.getResources().getString(R.string.uncheck_sex));
                btnAliPay.setTextColor(activity.getResources().getColor(R.color.text_gray_99));
                btnWeChart.setText(activity.getResources().getString(R.string.check_sex));
                btnWeChart.setTextColor(activity.getResources().getColor(R.color.main_color));
                payIsCan(1,""+paySureJson.getOrderId(),activity);
            }
        });
        btnAliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                btnWeChart.setText(activity.getResources().getString(R.string.uncheck_sex));
                btnWeChart.setTextColor(activity.getResources().getColor(R.color.text_gray_99));
                btnAliPay.setText(activity.getResources().getString(R.string.check_sex));
                btnAliPay.setTextColor(activity.getResources().getColor(R.color.main_color));
                payIsCan(2,""+paySureJson.getOrderId(),activity);
            }
        });

    }

    /**
     * 支付订单接口
     * @param type
     * @param getId
     * orderId	true	订单号
     * type	true	支付类型 1 微信 2 支付宝
     */
    public void payIsCan(int type,String getId,Activity activity){
        mActivity=activity;
        Map<String,String> maps=new HashMap<>();
        maps.put("orderId",getId);
        maps.put("type",""+type);
        Api.getInstanceService(Constants.Pay_URL).sureOrderPay(maps).enqueue(new BaseCallback<PayMoneyBean>() {
            @Override
            public void onResponse(Call<PayMoneyBean> call, PayMoneyBean result) {
                if(type==1){//微信的
                    Map<String,String> map=(Map<String, String>) result.getReturnData();
                    PayUtil.payForWx(activity,null,map);
                }else if(type==2){//支付宝
                    payApi_pay(result.getReturnData().toString(),activity);
                }
            }
        });
    }
    private Activity mActivity;
    /**
     * 支付宝支付
     * @param data
     * @param activity
     */
    public void payApi_pay(String data, Activity activity) {
//        final String payInfo = data.get("action");

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                Map<String, String>  result = alipay.payV2(data, true);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {//支付成功
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                ToastUtil.getToastEmail().ToastShow(mActivity,null,1,R.layout.toast_view,mActivity.getResources().getString(R.string.pay_sure));
                mActivity.startActivity(new Intent(mActivity,ResultPayActivity.class));
                mActivity.finish();

            } else {//支付失败
                Log.e("支付失败",""+payResult);
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。s
                RxToast.info(mActivity.getResources().getString(R.string.pay_cancel_get));
            }

        };
    };

    /**
     * 根据价格分类数据
     * @param list
     * @return
     */
    public Map<String,List<OrderListBean.OrderGoods>>  sortAmountList(List<OrderListBean.OrderGoods> list){
        TreeMap tm=new TreeMap();
        for(int i=0;i<list.size();i++){
            OrderListBean.OrderGoods s=list.get(i);
            if(tm.containsKey(""+s.getAmount())){//根据价格分类
                List<OrderListBean.OrderGoods> l11=(List<OrderListBean.OrderGoods>)tm.get(""+s.getAmount());
                l11.add(s);
            }else{
                List<OrderListBean.OrderGoods> tem=new ArrayList<>();
                tem.add(s);
                tm.put(""+s.getAmount(), tem);
            }
        }
        return tm;
    }
}